package csu.web.mypetstore.controller;

import csu.web.mypetstore.pojo.Account;
import csu.web.mypetstore.pojo.Product;
import csu.web.mypetstore.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@CrossOrigin
public class AccountController {


    @Autowired
    private AccountService accountService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ImageService imageService;

    @GetMapping("myAccount")
    public String myAccount(HttpSession session){
        return "account/MyAccount";
    }
    @GetMapping("cmsMyAccount")
    public String cmsMyAccount(HttpSession session){
        return "cms/account/MyAccount";
    }
    @PostMapping("register")
    @Transactional
    public String register(HttpSession session,
                           Model model,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("firstname") String firstname,
                           @RequestParam("lastname") String lastname,
                           @RequestParam("email") String email,
                           @RequestParam("phone") String phone,
                           @RequestParam("address1") String address1,
                           @RequestParam("address2") String address2,
                           @RequestParam("city") String city,
                           @RequestParam("state") String state,
                           @RequestParam("zip") String zip,
                           @RequestParam("country") String country,
                           @RequestParam("code") String code,
                           @RequestParam("image") MultipartFile file
    ) {

        String msg;
        String realCode = (String) session.getAttribute("code");
        Account registerAccount = accountService.getAccount(username, password);
        if (registerAccount != null) {
            msg = "Username already exists";
            model.addAttribute("signOnMsg", msg);
            return "account/NewAccountForm";
        } else if (!code.equals(realCode)) {
            msg = "Invalid code";
            model.addAttribute("signOnMsg", msg);
            return "account/NewAccountForm";
        } else {
            accountService.insertSignon(username, password,imageService.saveImage(file,username));
            accountService.insertAccount(username,password, email, firstname, lastname, "ok", address1, address2, city, state, Integer.valueOf(1), country, phone);
            return "redirect:/mainForm";

        }
    }
    @PostMapping("cmsRegister")
    @Transactional
    public String cmsRegister(HttpSession session,
                           Model model,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("firstname") String firstname,
                           @RequestParam("lastname") String lastname,
                           @RequestParam("email") String email,
                           @RequestParam("phone") String phone,
                           @RequestParam("address1") String address1,
                           @RequestParam("address2") String address2,
                           @RequestParam("city") String city,
                           @RequestParam("state") String state,
                           @RequestParam("zip") String zip,
                           @RequestParam("country") String country,
                           @RequestParam("code") String code,
                           @RequestParam("image") MultipartFile file
    ) {

        String msg;
        String realCode = (String) session.getAttribute("code");
        Account registerAccount = accountService.getAccount(username, password);
        if (registerAccount != null) {
            msg = "Username already exists";
            model.addAttribute("signOnMsg", msg);
            return "cms/account/NewAccountForm";
        } else if (!code.equals(realCode)) {
            msg = "Invalid code";
            model.addAttribute("signOnMsg", msg);
            return "cms/account/NewAccountForm";
        } else {
            accountService.insertSignon(username, password,imageService.saveImage(file,username));
            accountService.insertAccount(username,password, email, firstname, lastname, "ok", address1, address2, city, state, Integer.valueOf(1), country, phone);
            return "redirect:/cms/mainForm";

        }
    }

    @PostMapping("save")
    @Transactional
    public String saveInformation(
            @RequestParam("username") String username,
            @RequestParam("firstname") String firstname,
            @RequestParam("lastname") String lastname,
            @RequestParam("email") String email,
            @RequestParam("phone") String phone,
            @RequestParam("address1") String address1,
            @RequestParam("address2") String address2,
            @RequestParam("city") String city,
            @RequestParam("state") String state,
            @RequestParam("zip") String zip,
            @RequestParam("country") String country,
            @RequestParam("password") String password,
            HttpSession session) {
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        loginAccount.setUsername(username);
        loginAccount.setFirstname(firstname);
        loginAccount.setLastname(lastname);
        loginAccount.setEmail(email);
        loginAccount.setPhone(phone);
        loginAccount.setAddr1(address1);
        loginAccount.setAddr2(address2);
        loginAccount.setCity(city);
        loginAccount.setCountry(country);
        if (zip != null && !zip.trim().isEmpty()) {
            loginAccount.setZip(Integer.valueOf(zip));
        } else {
            loginAccount.setZip(null); // 或者设为默认值，例如 0
        }
        loginAccount.setState(state);
        loginAccount.setPassword(password);
        System.out.println("Username from request: " + username);
        try {

            accountService.updateAccount(loginAccount);
        } catch (Exception e) {
            e.printStackTrace(); // 建议使用日志框架记录异常
        }
        // 更新Session中的账户信息
        System.out.println("username: " + username);
        // 重定向到主页面
        return "redirect:/mainForm";
    }


    @PostMapping("cmsSave")
    @Transactional
    public String cmsSaveInformation(
            @RequestParam("username") String username,
            @RequestParam("firstname") String firstname,
            @RequestParam("lastname") String lastname,
            @RequestParam("email") String email,
            @RequestParam("phone") String phone,
            @RequestParam("address1") String address1,
            @RequestParam("address2") String address2,
            @RequestParam("city") String city,
            @RequestParam("state") String state,
            @RequestParam("zip") String zip,
            @RequestParam("country") String country,
            @RequestParam("password") String password,
            HttpSession session) {
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        loginAccount.setUsername(username);
        loginAccount.setFirstname(firstname);
        loginAccount.setLastname(lastname);
        loginAccount.setEmail(email);
        loginAccount.setPhone(phone);
        loginAccount.setAddr1(address1);
        loginAccount.setAddr2(address2);
        loginAccount.setCity(city);
        loginAccount.setCountry(country);
        if (zip != null && !zip.trim().isEmpty()) {
            loginAccount.setZip(Integer.valueOf(zip));
        } else {
            loginAccount.setZip(null); // 或者设为默认值，例如 0
        }
        loginAccount.setState(state);
        loginAccount.setPassword(password);
        System.out.println("Username from request: " + username);
        try {

            accountService.updateAccount(loginAccount);
        } catch (Exception e) {
            e.printStackTrace(); // 建议使用日志框架记录异常
        }
        // 更新Session中的账户信息
        System.out.println("username: " + username);
        // 重定向到主页面
        return "redirect:/cmsMainForm";
    }

    @PostMapping("signOn")
    @Transactional
    public String signOn(HttpSession session,@RequestParam("username") String username, @RequestParam("password") String password, Model model){


        String msg="";

        if(!validate(username,password))
        {
            model.addAttribute("signOnMsg",msg);
            return "account/signon";
        }else {
            Account loginAccount = accountService.getAccount(username, password);
            if(loginAccount == null)
            {

                model.addAttribute(" signOnMsg",  "用户名或密码错误");
                return "account/signon";
            }else {
               loginAccount.setPassword(password);
               loginAccount.setUsername(username);
                session.setAttribute("loginAccount", loginAccount);
                if(loginAccount.isListOption())
                {

                    List<Product> myList =productService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList", myList);
                }
                System.out.println("----------------------loginAccount:---------------------- " );
                return "redirect:/mainForm";
            }
        }
    }
    @PostMapping("cmsSignOn")
    @Transactional
    public String cmsSignOn(HttpSession session,@RequestParam("username") String username, @RequestParam("password") String password, Model model){


        String msg="";

        if(!validate(username,password))
        {
            model.addAttribute("signOnMsg",msg);
            return "account/signon";
        }else {
            Account loginAccount = accountService.getAccount(username, password);
            if(loginAccount == null)
            {

                model.addAttribute(" signOnMsg",  "用户名或密码错误");
                return "account/signon";
            }else {
                loginAccount.setPassword(password);
                loginAccount.setUsername(username);
                session.setAttribute("loginAccount", loginAccount);
                if(loginAccount.isListOption())
                {

                    List<Product> myList =productService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList", myList);
                }
                System.out.println("----------------------loginAccount:---------------------- " );
                return "redirect:/cmsMainForm";
            }
        }
    }
    private boolean validate(String username, String password) {

        String msg = "";
        if (username == null || username.equals("")) {
            msg = "用户名不能为空";
            return false;
        }
        if (password == null || password.equals("")) {
            msg="密码不能为空";
            return false;
        }
        return true;
    }
    @GetMapping("cmsSignOut")
    public String cmsSignOut(HttpSession session){

        session.invalidate();

        return "redirect:cmsMainForm";
    }
    @GetMapping("signOut")
    public String signOut(HttpSession session){

        session.invalidate();

        return "redirect:/mainForm";
    }
    @GetMapping("usernameExist")
    @ResponseBody
    @Transactional
    public String usernameExist(HttpSession session, @RequestParam("username") String username){
        Account result = accountService.getAccount(username);
        if (result == null) {
            return "Not Exist";
        } else {
            return "Exist";
        }
    }
    @PostMapping("delete")
    @Transactional
    public String deleteAccount(HttpSession session) {
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        try {
            // 删除用户
            accountService.deleteAccount(loginAccount.getUsername());
            // 清除 Session
            session.invalidate();
        } catch (Exception e) {
            e.printStackTrace(); // 记录异常日志
        }
        if (loginAccount == null) {
            return "redirect:/signonForm"; // 如果用户未登录，重定向到登录页面
        }
        return "redirect:/signonForm"; // 重定向到登录页面
    }
}
